package com.huawei.cloud.phone.management.adapter.user;

import com.huawei.cloud.phone.management.adapter.utils.HttpUtils;
import com.huawei.cloud.phone.management.common.exception.AuthFailedException;
import com.huawei.cloud.phone.management.common.utils.Constants;
import com.huawei.cloud.phone.management.domain.user.UserDomainService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Optional;

@Slf4j
@AllArgsConstructor
@Aspect
@Component
@Order(99)
public class LoginCheckerAspect {
    private final UserDomainService userDomainService;

    /**
     * 校验用户的登录状态
     */
    @Before("@annotation(com.huawei.cloud.phone.management.adapter.user.LoginChecker)")
    public void checkLoginStatus() {
        log.info("check login status");
        Optional<String> sessionId = HttpUtils.getDataFromHeader(Constants.SESSION_ID);
        Optional<String> token = HttpUtils.getDataFromHeader(Constants.TOKEN);
        if (!sessionId.isPresent() || !token.isPresent()) {
            throw new AuthFailedException();
        }
        userDomainService.auth(sessionId.get(), token.get());
    }
}
